﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenSource.UPnP;
using System.IO;
using System.Collections;
using System.Reflection;

namespace ApplicationCliente1
{
    class ClientApplicationCliente1
    {
        private UPnPSmartControlPoint cp;
        
        /**
           * \nb_dev1        le nombre de devices connectés
        */
        private int nb_dev;
        static ArrayList _zones = new ArrayList();
        UPnPArgument[] args2 = new UPnPArgument[3];
        MainWindow mainwindow;

        public ClientApplicationCliente1(MainWindow mainw)
        {
            nb_dev = 0;
            mainwindow = mainw;
        }

        static public ArrayList Zones
        {
            get { return _zones; }
            set { _zones = value; }
        }

        string m;
        string resultatReservation;
        string IdReservation;

        Boolean b = false;

        /**
        * \Search               méthode intermédiaire dans la recherche d'un device sur le réseau
        
        */
        public void Search()
        {
            Console.WriteLine("/////////////////////////////////////////////////////////////////");

            m = MainWindow.nomdispo;

            Console.WriteLine("Nom du dispooooooooo est : " + MainWindow.nomdispo);

            Console.WriteLine("/////////////////////////////////////////////////////////////////");

            cp = new UPnPSmartControlPoint(new UPnPSmartControlPoint.DeviceHandler(NewDevice));
            cp.OnRemovedDevice += new UPnPSmartControlPoint.DeviceHandler(DeviceQuit);
            cp.Rescan();
        }
        /**
        * \NewDevice                pour la recherche d'un device sur le réseau.
         * \param    sender1        sender1 pour le sender qui a declencher la methode.
        * \param    device          device est le device qui va apparaitre sur réseau.
         */
        public void NewDevice(UPnPSmartControlPoint sender, UPnPDevice device)
        {

            if (device.FriendlyName != MainWindow.nomdispo)
            {
                Console.WriteLine("ignoring " + device.FriendlyName);
                return;
            }

            nb_dev++;
            
           
            _zones.Add(nb_dev);

            _zones.Add(MainWindow.nomdispo);

            Console.WriteLine(MainWindow.nomdispo + " found: " + nb_dev);
        }



        /**
        * \DeviceQuit               affiche un message si un device a quitté le réseau
        * \param    sender1         sender1 pour le sender qui a déclenché la méthode.
        * \param    device          device est le device qui va quitter le réseau.
        */

        public void DeviceQuit(UPnPSmartControlPoint sender, UPnPDevice device)
        {

            Console.Out.WriteLine(MainWindow.nomdispo + " quit: " + nb_dev);

            nb_dev--;
        }



        /**
        * \getFile                  pour l'envoie du fichier de description au serveur d'affichage
        * \param    sender1         sender1 pour le sender qui a déclenché la méthode.
        * \param    device          device est le device qui va quitter le réseau.
        */
        public void getFile(UPnPSmartControlPoint sender, UPnPDevice device)
        {

            Console.WriteLine("Name pour la 2 éme fois est " + MainWindow.nomdispo);
            if (device.FriendlyName == MainWindow.nomdispo)
            {
                Console.WriteLine("trueeeeeeeeeeeeeeeee");

                UPnPArgument[] args = new UPnPArgument[3];


                UPnPService serv = device.GetService("Sample");


                if (serv == null)
                {
                    Console.Error.WriteLine("Could not find service `Sample' in device " + nb_dev);
                }

                Console.WriteLine("service  Sample  in device `" + MainWindow.nomdispo + "' is Found");


                String text = " ";

                text = OpenFile();


                if (text == null)
                {
                    Console.WriteLine("File is empty");

                }

                args[0] = new UPnPArgument("InFile", text);
                args[1] = new UPnPArgument("name", "ServeurClientUPnP1");
                args[2] = new UPnPArgument("IdReservation", IdReservation);
                serv.InvokeSync("loadFile", args);


            }
        }


        /**
        * \sendFile              méthode intérmediaire pour l'envoie du fichier de description au serveur d'affichage
        */

        
        public void sendFile()
        {
            cp = new UPnPSmartControlPoint(new UPnPSmartControlPoint.DeviceHandler(getFile));
        
        }


        /**
        * \OpenFile               ouverture et la lecture du fichier de description
        */
        public String OpenFile()
        {

            string txt = "";

            StringWriter writer = new StringWriter();

            try
            {
                StreamReader reader = File.OpenText("d:/service3.xaml");

                String line = "";
                try
                {

                    line = reader.ReadLine();

                    while (line != null)
                    {
                        writer.Write(line);
                        Console.WriteLine("line=" + line);
                        line = reader.ReadLine();
                    }
                    reader.Close();
                }
                catch (System.IO.EndOfStreamException) { }
            }

            catch (FileNotFoundException ex) { }

            txt = writer.ToString();

            Console.WriteLine("Fin lecture du File: \n " + txt);

            return txt;
        }





        public void sendParametre2() {

            cp = new UPnPSmartControlPoint(new UPnPSmartControlPoint.DeviceHandler(getParametreInterface2));

        }



        public void getParametreInterface2(UPnPSmartControlPoint sender, UPnPDevice device)
        {

            if (device.FriendlyName == MainWindow.nomdispo)
            {
                Console.WriteLine("trueeeeeeeeeeeeeeeee");

                UPnPArgument[] args = new UPnPArgument[2];


                UPnPService serv = device.GetService("Sample");


                if (serv == null)
                {
                    Console.Error.WriteLine("Could not find service `Sample' in device " + nb_dev);
                }

                Console.WriteLine("service  Sample  in device `" + MainWindow.nomdispo + "' is Found");

                double d1=926;
                double d2=773;
                args[0] = new UPnPArgument("width", d1);
                args[1] = new UPnPArgument("height", d2);

                serv.InvokeSync("loadParametreInterface", args);


          }

        }



        public void getParametreInterface(int width, int height)
        {


            Console.WriteLine("w= " + width);
            Console.WriteLine("H= " + height);

            args2[0] = new UPnPArgument("name", "ApplicationCommunicante1");
            args2[1] = new UPnPArgument("width", width);
            args2[2] = new UPnPArgument("height", height);

            cp = new UPnPSmartControlPoint(new UPnPSmartControlPoint.DeviceHandler(sendParametreInterface));

        }



        public void sendParametreInterface(UPnPSmartControlPoint sender, UPnPDevice device)
        {

            if (device.FriendlyName == MainWindow.nomdispo)
            {

                UPnPService serv = device.GetService("Sample");

                if (serv == null)
                {
                    Console.Error.WriteLine("Could not find service `Sample' in device ");
                }



                string retval;


                try
                {
                    retval = (string)serv.InvokeSync("recupereParametreInterface", args2);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e);
                    retval = "ERROR";
                }

               
                if (retval != null)
                {

                    Console.WriteLine("valeuuuuuuuuuuuuuuurrrrrrrrrrrrrrrrr de retval est : " + retval);
                    resultatReservation = retval;
                    Console.WriteLine("resultatReservation = " + resultatReservation);
                    string commande = resultatReservation.Substring(resultatReservation.IndexOf("Ton Identifiant de Reservation"));

                    Console.WriteLine("la commande à afficher est: " + commande);
                    string cm = commande.Substring(commande.IndexOf("=") + 2);
                    Console.WriteLine("la cm à afficher est: " + cm);
                    IdReservation = cm;


                }

                mainwindow.RefreshMessage2(retval);


            }



        }


        public void finsentDecision()
        {

            cp = new UPnPSmartControlPoint(new UPnPSmartControlPoint.DeviceHandler(finsentDecisionFinale));

        }


        public void finsentDecisionFinale(UPnPSmartControlPoint sender, UPnPDevice device)
        {

            if (device.FriendlyName == MainWindow.nomdispo)
            {
                Console.WriteLine("trueeeeeeeeeeeeeeeee");

                UPnPService serv = device.GetService("Sample");

                if (serv == null)
                {
                    Console.Error.WriteLine("Could not find service `Sample' in device ");
                }

                Console.WriteLine("service  Sample2 is Found");

                UPnPArgument[] args3 = new UPnPArgument[1];

                string decisionFinale = mainwindow.DecisionFinale;

                while (decisionFinale == "")
                {
                    Console.WriteLine("sleeeeeeeeeeeeeeeeeeppp");
                    decisionFinale = mainwindow.DecisionFinale;
                }
                Console.WriteLine(decisionFinale);
                args3[0] = new UPnPArgument("decisionFinale", decisionFinale);

                serv.InvokeSync("updateresultatFinal", args3);


            }




        }




    }
}

